<template>
	<div>
		<!--面包屑-->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }"> 首页</el-breadcrumb-item>
			<el-breadcrumb-item>商品管理</el-breadcrumb-item>
			<el-breadcrumb-item>添加商品</el-breadcrumb-item>
		</el-breadcrumb>

		<!--卡片视图-->
		<el-card>
			<!--警告信息-->
			<el-alert title="添加商品信息" type="info" center show-icon :closable="false"> </el-alert>

			<!--步骤条-->
			<el-steps :active="acriveIndex - 0" align-center finish-status="success">
				<el-step title="基本信息"></el-step>
				<el-step title="商品参数"></el-step>
				<el-step title="商品属性"></el-step>
				<el-step title="商品图片"></el-step>
				<el-step title="商品内容"></el-step>
				<el-step title="完成"></el-step>
			</el-steps>

			<!--tab栏-->
			<el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-position="top">
				<el-tabs v-model="acriveIndex" tab-position="left" :before-leave="beforeTableave" @tab-click="tabClicked">
					<el-tab-pane label="基本信息" name="0">
						<!--商品名称-->
						<el-form-item label="商品名称" prop="goods_name">
							<el-input v-model="addForm.goods_name"></el-input>
						</el-form-item>
						<!--商品价格-->
						<el-form-item label="商品价格" prop="goods_price">
							<el-input v-model="addForm.goods_price"></el-input>
						</el-form-item>
						<!--商品重量-->
						<el-form-item label="商品重量" prop="goods_weight">
							<el-input v-model="addForm.goods_weight"></el-input>
						</el-form-item>
						<!--商品数量-->
						<el-form-item label="商品数量" prop="goods_number">
							<el-input v-model="addForm.goods_number"></el-input>
						</el-form-item>
						<!--商品分类-->
						<el-form-item label="商品分类">
							<el-cascader v-model="addForm.goods_cat" :options="goodsCateList" :props="cateProps" @change="handleChange"></el-cascader>
						</el-form-item>
					</el-tab-pane>
					<el-tab-pane label="商品参数" name="1">
						<el-form-item :label="item.attr_name" v-for="item in manyData" :key="item.attr_id">
							<el-checkbox-group v-model="item.attr_vals">
								<el-checkbox border :label="item2" v-for="(item2, index) in item.attr_vals" :key="index"></el-checkbox>
							</el-checkbox-group>
						</el-form-item>
					</el-tab-pane>
					<el-tab-pane label="商品属性" name="2">
						<el-form-item :label="items.attr_name" v-for="items in onlyData" :key="items.attr_id">
							<el-input v-model="items.attr_vals"></el-input>
						</el-form-item>
					</el-tab-pane>
					<el-tab-pane label="商品图片" name="3">
						<el-upload :headers="headerObj" :action="uploadUrl" :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture" :on-success="uploadSuccess">
							<el-button size="small" type="primary">点击上传</el-button>
							<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
						</el-upload>
					</el-tab-pane>
					<el-tab-pane label="商品内容" name="4">
						<!--富文本编辑器-->
						<quill-editor v-model="addForm.goods_introduce"></quill-editor>
						<el-button class="addBtn" type="primary" @click="addGoods">添加商品</el-button>
					</el-tab-pane>
				</el-tabs>
			</el-form>
		</el-card>

		<!--图片展示对话框-->
		<el-dialog title="图片预览" :visible.sync="dialogVisible" width="50%">
			<img :src="PreviewPath" style="width: 100%" />
		</el-dialog>
	</div>
</template>

<script>
import _ from 'lodash'
export default {
	data() {
		return {
			// 商品分类数据
			goodsCateList: [],
			cateProps: { expandTrigger: 'hover', value: 'cat_id', label: 'cat_name', children: 'children' },

			// 步骤条和tab栏联动属性
			acriveIndex: '0',
			// form表单内容
			addForm: {
				goods_name: '',
				goods_price: 0,
				goods_weight: 0,
				goods_number: 0,
				// 商品所属的分类数组
				goods_cat: [],
				pics: [],
				goods_introduce: '',
        attrs:[]
			},
			// form表单规则
			addFormRules: {
				goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
				goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
				goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
				goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
			},

			// 动态参数
			manyData: [],
			// 静态属性
			onlyData: [],
			// 上传图片的url地址
			uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
			// 上传的请求头信息
			headerObj: {
				Authorization: window.sessionStorage.getItem('token'),
			},
			PreviewPath: '',
			dialogVisible: false,
		}
	},

	created() {
		this.getGoodsCate()
	},
	methods: {
		// 获取商品分类数据
		async getGoodsCate() {
			const { data: res } = await this.$http.get('categories')
			if (res.meta.status !== 200) {
				return this.$message.error('获取分类数据失败')
			} else {
				this.goodsCateList = res.data
				// console.log(this.goodsCateList)
			}
		},
		// 选择分类时触发的事件
		handleChange() {
			console.log(this.addForm.goods_cat)
			// 只允许选择第三级分类
			if (this.addForm.goods_cat.length !== 3) {
				this.addForm.goods_cat = []
			}
		},

		//tab栏切换前的钩子函数
		beforeTableave(activeName, oldActiveName) {
			if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
				this.$message.error('请选择商品分类')
				return false
			}
		},

		// tab标签栏点击函数
		async tabClicked() {
			// 如果点击acriveIndex为1的标签栏，发起axios请求
			if (this.acriveIndex === '1') {
				const { data: res } = await this.$http.get(`categories/${this.catId}/attributes`, { params: { sel: 'many' } })
				if (res.meta.status !== 200) {
					return this.$message.error('获取动态参数失败')
				} else {
					res.data.forEach(item => {
						// 字符串转数组
						item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
					})
					this.manyData = res.data
					console.log(this.manyData)
				}
			} else if (this.acriveIndex === '2') {
				const { data: res } = await this.$http.get(`categories/${this.catId}/attributes`, { params: { sel: 'only' } })
				if (res.meta.status !== 200) {
					return this.$message.error('获取静态属性失败')
				} else {
					this.onlyData = res.data
					console.log(this.onlyData)
				}
			}
		},

		// 处理图片预览的事件
		handlePreview(file) {
			console.log(file)
			this.PreviewPath = file.response.data.url
			this.dialogVisible = true
		},

		// 处理图片删除的事件
		handleRemove(file) {
			console.log(file)
			const deletePath = file.response.data.tmp_path
			const i = this.addForm.pics.findIndex(x => x.pic === deletePath)
			this.addForm.pics.splice(i, 1)
			// console.log(this.addForm)
		},

		// 上传成功之后的操作事件
		uploadSuccess(res) {
			// 1、拼接图片
			const picInfo = { pic: res.data.tmp_path }
			this.addForm.pics.push(picInfo)
			// console.log(this.addForm)
		},

		// 添加商品
		addGoods() {
			this.$refs.addFormRef.validate( async valid => {
				if (!valid) {
					return this.$message.error('请填写必要的表单项')
				}
        // 做深拷贝，把addform复制一份做ajax，这样不影响分类使用的数组数据，同时又能不影响我们提交的参数
				const form = _.cloneDeep(this.addForm)
        // 把拷贝出来的数据中的goodcat数组转换成字符串，此刻并不影响addform中的数据
        form.goods_cat = form.goods_cat.join(',')

        // 动态参数处理
        this.manyData.forEach(item => {
          const newInfo = {attr_id:item.attr_id,attr_value:item.attr_vals.join(' ')}
          form.attrs.push(newInfo)
        })
        // 静态参数处理
        this.onlyData.forEach(item=>{
          const newInfo = {attr_id:item.attr_id,attr_value:item.attr_vals}
          form.attrs.push(newInfo)
        })

        // 发起请求
       const {data:res} = await this.$http.post('goods',form)
        if(res.meta.status !== 201){
          console.log(res)
          return this.$message.error('添加商品失败')
        }else{
          this.$message.success('添加商品成功')
          // 编程式导航
          await this.$router.push('/goods')
        }
			})
		},
	},

	// 计算属性
	computed: {
		catId: function () {
			if (this.addForm.goods_cat.length === 3) {
				return this.addForm.goods_cat[this.addForm.goods_cat.length - 1]
			}
		},
	},
}
</script>

<style lang="less" scoped>
.el-checkbox {
	margin: 0 10px 0 0 !important;
}
.addBtn {
	margin-top: 10px;
}
</style>
